package com.tvserials.notification.fragments;

import android.content.Context;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.tvserials.notification.R;
import com.tvserials.notification.adapters.TvSerialsExpandableListAdapter;
import com.tvserials.notification.dto.Serial;
import com.tvserials.notification.exceptions.NetworkConnectionException;
import com.tvserials.notification.preferences.SharedPreferencesUtils;
import com.tvserials.notification.services.NotificationService;
import com.tvserials.notification.services.ServiceFactory;
import com.tvserials.notification.utils.DisplayToastMessage;
import com.tvserials.notification.utils.NetworkUtils;
import com.tvserials.notification.utils.VOUtils;
import com.tvserials.notification.vo.SourceType;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by Alex on 17.04.2014.
 */
public class DefaultSerialsFragment extends Fragment {
    private final SourceType sourceType;
    private ExpandableListView listView;
    private List<Serial> serials = new ArrayList<Serial>();
    private ProgressBar progressBar;
    private PopupWindow popup;
    private ImageView imageView;

    public DefaultSerialsFragment(SourceType type) {
        sourceType = type;
    }

    public SourceType getSourceType() {
        return sourceType;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.serials_list, container, false);
        listView = (ExpandableListView) rootView.findViewById(R.id.listView1);
//        listView.setTextFilterEnabled(true);
//        listView.setOnScrollListener(new ScrollListener());
        progressBar = (ProgressBar) rootView.findViewById(R.id.signProgressBar);

        loadSerials();
        return rootView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void loadSerials() {
        if (NetworkUtils.isConnected(getActivity())) {
            new LoadSerialsList().execute();
        } else {
            getActivity().runOnUiThread(new DisplayToastMessage(getActivity(), R.string.no_network));
        }
    }

    /**
     * Map signed serials on provided list
     *
     * @param listItems
     */
    private void updateSelectedValues(List<Serial> listItems) {
        List<Serial> serialList = SharedPreferencesUtils.getSerialsList(getApplicationContext());
        if (VOUtils.isListNotEmpty(serialList) && VOUtils.isListNotEmpty(listItems)) {
            for (Serial item : listItems) {
                item.setSelected(serialList.contains(item));
            }
        }
    }

    public Context getApplicationContext() {
        if (getActivity() != null) {
            return getActivity().getApplicationContext();
        }
        return null;
    }

    private class ScrollListener implements AbsListView.OnScrollListener {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            System.out.println("scroll" + view.getFirstVisiblePosition());
            if (scrollState == SCROLL_STATE_IDLE) {
                if (view.getFirstVisiblePosition() != 0 && (popup == null || !popup.isShowing())) {
                    //TODO use position bottom right corner as position
                    Point p = new Point(20, 200);
                    showPopup(p);
                }
            } else if (popup != null) {
                popup.dismiss();
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    }

    private class LoadSerialsList extends AsyncTask<Void, Void, List<Serial>> {
        @Override
        protected void onPreExecute() {
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected List<Serial> doInBackground(Void... voids) {
            try {
                NotificationService pageParser = ServiceFactory.getNotificationService();
                serials = pageParser.getSerials(sourceType);
            } catch (NetworkConnectionException e) {
                FragmentActivity activity = getActivity();
                if (activity != null) {
                    activity.runOnUiThread(new DisplayToastMessage(getApplicationContext(), R.string.network_timeout));
                }
            }
//             catch (PageParseException e) {
//                getActivity().runOnUiThread(new DisplayToastMessage(getApplicationContext(), R.string.parse_error));
//            }
            return serials;
        }

        @Override
        protected void onPostExecute(List<Serial> serialVOs) {
            progressBar.setVisibility(View.GONE);
            updateSelectedValues(serialVOs);
            updateListAdapter(serialVOs);
        }

    }

    private void showPopup(Point p) {
        int popupWidth = 120;
        int popupHeight = 100;

        // Inflate the popup_layout.xml
        ViewGroup rootView = (ViewGroup) getActivity().findViewById(R.id.popup);
        LayoutInflater layoutInflater = (LayoutInflater) getActivity()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = layoutInflater.inflate(R.layout.go_top_popup, rootView, false);

        // Creating the PopupWindow
        popup = new PopupWindow(getActivity());
        popup.setContentView(layout);
        popup.setWidth(popupWidth);
        popup.setHeight(popupHeight);
        popup.setFocusable(false);

        // Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
        int OFFSET_X = 30;
        int OFFSET_Y = 30;

        // Displaying the popup at the specified location, + offsets.
        popup.showAtLocation(layout, Gravity.NO_GRAVITY, p.x + OFFSET_X, p.y + OFFSET_Y);

        // Getting a reference to Close button, and close the popup when clicked.
        Button close = (Button) layout.findViewById(R.id.btnGoTop);
        close.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                listView.setSelection(0);
                popup.dismiss();
            }
        });
    }

    private void updateListAdapter(List<Serial> listItems) {
        Context applicationContext = getApplicationContext();
        if (applicationContext != null && !listItems.isEmpty()) {

            Map<String, List<Serial>> stringListMap = VOUtils.groupSerialsAlphabetically(listItems);
            List<String> serialsCategories = new ArrayList<String>(stringListMap.keySet());
            Collections.sort(serialsCategories);
            TvSerialsExpandableListAdapter adapter = new TvSerialsExpandableListAdapter(applicationContext,
                    serialsCategories, stringListMap, listItems.get(0).getSourceType());
            listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }
}
